package com.aibaixun.web.controller.listen;

import javax.annotation.PostConstruct;

import cn.hutool.json.JSONUtil;
import com.aibaixun.system.service.DicmSignalhService;
import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;


@Configuration
public class DicmMqttConsumer {

    @Value("${spring.mqtt.url}")
    private String hostUrl;


    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${commonConfig.isOut}")
    private Boolean isOut;

    /**
     * 客户端对象
     */
    private MqttClient client;

    @Autowired
    private DicmSignalhService dicmSignalhService;

    private static DicmMqttConsumer dicmMqttConsumer;

    /**
     * 在bean初始化后连接到服务器
     */
    @PostConstruct
    public void init(){
        dicmMqttConsumer = this;
        dicmMqttConsumer.dicmSignalhService = this.dicmSignalhService;
        if(!isOut){
            connect();
        }
    }


    /**
     * 客户端连接服务端
     */
    public void connect(){
        System.out.println("开始建立mqtt链接===========================");
        try {
            //创建MQTT客户端对象
            client = new MqttClient(hostUrl,clientId,new MemoryPersistence());
            //连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session，设置为false表示服务器会保留客户端的连接记录，客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
            //设置为true表示每次连接到服务端都是以新的身份
            options.setCleanSession(true);
            //设置超时时间，单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒，表示服务器每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            options.setWill("willTopic",(clientId + "与服务器断开连接").getBytes(),0,false);
            //设置回调
            client.setCallback(new MqttCallback(){

                @Override
                public void connectionLost(Throwable throwable) {
                    System.out.println("与服务器断开连接，可重连");
                    try {
                        // 等待一段时间再尝试重新连接
                        Thread.sleep(1000);
                        dicmMqttConsumer.connect();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    System.out.println("接收到mqtt推送的性能数据：topic="+topic+"   数据："+JSONUtil.parse(mqttMessage));
                    //消息处理后续业务逻辑
                    try {
                        JSONObject jsonData = JSONObject.parseObject(new String(mqttMessage.getPayload()));
                        dicmSignalhService.handleJsonData(jsonData);
                    }catch (Exception e){
                        e.printStackTrace();
                        System.out.println("MQTT数据解析异常："+e.getMessage());
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    System.out.println(String.format("接收消息成功"));
                }
            });
            client.connect(options);
            //订阅主题
            //消息等级，和主题数组一一对应，服务端将按照指定等级给订阅了主题的客户端推送消息
            int[] qos = {1};
            //主题
//            String[] topics = {"iot-rt-data"};
            String[] topics = {"iot-rt-data/zt"};
            //订阅主题
            client.subscribe(topics,qos);
            System.out.println("建立mqtt链接成功===========================");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    /**
     * 断开连接
     */
    public void disConnect(){
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }



    /**
     * 订阅主题
     */
    public void subscribe(String topic,int qos){
        try {
            client.subscribe(topic,qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

